package com.xjy.rpc.netty.handler.server;

import com.xjy.rpc.config.Constant;
import com.xjy.rpc.netty.message.RpcRequest;
import com.xjy.rpc.netty.message.RpcResponse;
import com.xjy.rpc.netty.message.RpcMessage;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Random;
import java.util.concurrent.TimeUnit;

public class ServerMessageHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext channelHandlerContext, Object o) throws Exception {
        //TODO 加入心跳解析
        if (o instanceof String){
            channelHandlerContext.channel().writeAndFlush("copy that!");
        }
        RpcRequest msg = (RpcRequest) o;
        String interfaceName = msg.getInterfaceName();
        Class<?> aClass = Class.forName(interfaceName);
        Method method = aClass.getMethod(msg.getMethodName());
        //TODO 这里异步执行返回method执行后的结果
        Object invoke = null;
        Exception exception = null;
        try {
            invoke = method.invoke(aClass.newInstance());
        } catch (Exception e) {
            e.printStackTrace();
            invoke = null;
            exception = e;
        }
        System.out.println(aClass.getClasses());
        //全包名
        System.out.println(aClass.getName());
        System.out.println(invoke);
        //构建返回消息体
        RpcMessage rpcMessage = new RpcMessage();
        rpcMessage.setMessageType(Constant.MESSAGE_TYPE_RES);
        rpcMessage.setRequestId(msg.getRequestId());;
        rpcMessage.setExpireTime(5000);
        rpcMessage.setUnit(TimeUnit.SECONDS);
        RpcResponse response = new RpcResponse();
        response.setResult(invoke);
        response.setRequestId(msg.getRequestId());
        response.setException(exception);
        rpcMessage.setBody(response);
        channelHandlerContext.writeAndFlush(rpcMessage);
    }
}
